const signModel = require("../model/sign");
const newUserActiveModel = require("../model/newUserActive");
exports.addSharTextRecord = async (unionId, openId, dateStr) => {
    const pool = await mysqlUtil();
    await pool.beginTransaction();
    try {
        /*const isFocusWxPub = await signModel.isFocusWxPub(pool, unionId, openId);
        if (!isFocusWxPub || isFocusWxPub.status == 0) {
            return {
                isFocusWxPub: false,
                addSharTextRecordResult: false
            }
        }*/
        let nowDateStr = moment().format('YYYYMMDDHHmmss');
        const activeConfigInfo = await newUserActiveModel.h5activeConfig(pool, 2);
        let activeOk = activeConfigInfo.startTime <= nowDateStr && activeConfigInfo.endTime > nowDateStr;
        //查询参加合同的模板
        let shareAmout = activeConfigInfo.redAmount;
        console.log(14, '---dateStr---', dateStr)
        const redEnvlopRecord = await signModel.hasDateRedEnvlopRecord(pool, unionId, openId, dateStr.substring(0, 8), 'shareText');
        console.log('红包记录', unionId, openId, dateStr.substring(0, 8), redEnvlopRecord);
        //当天已转发过，不再次记录到发放红包记录中
        if (!redEnvlopRecord && activeOk) {
            //红包发放记录
            await signModel.addRedEnvlopRecord(pool, {
                open_id: openId,
                union_id: unionId,
                create_time: dateStr,
                date_str: dateStr.substring(0, 8),
                status: 0, //默认转发文章后，未发放红包,
                amount: shareAmout,
                active_type: 'shareText'
            })
        }
        const addSharTextRecordResult = await signModel.addSharTextRecord(pool, {
            open_id: openId,
            union_id: unionId,
            create_time: dateStr,
            active_type: 'shareText'
        })

        await pool.commit();
        return {
            // isFocusWxPub: true,
            addSharTextRecordResult
        }
    } catch (error) {
        await pool.rollback();
        throw error;
    } finally {
        pool.close();
    }
}

exports.isFocusWxPub = async (unionId, openId) => {
    const pool = await mysqlUtil();
    const isFocusWxPub = await signModel.isFocusWxPub(pool, unionId, openId);
    pool.close();
    return isFocusWxPub;
}

//查询红包记录发放结果
exports.queryDateStrRedEnvByStatus = async (status = 0, dataStr) => {
    const pool = await mysqlUtil();
    const userArray = await signModel.queryDateStrRedEnvByStatus(pool, status, dataStr);
    pool.close();
    return userArray;
}



//批量给没有发红包的用户使用
exports.batchUpdateRedEnvopStatus = async (status = 1, openIds, dataStr, activeTYpe) => {
    const pool = await mysqlUtil();
    const result = await signModel.batchUpdateRedEnvopStatus(pool, status, openIds, dataStr, activeTYpe);
    pool.close();
    return result;

}